package com.project.isaacwiki.interceptor;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.project.isaacwiki.util.JwtUtil;
import com.project.isaacwiki.util.Result;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

@Component
public class InterceptorToken implements HandlerInterceptor {

    // 创建ObjectMapper对象，用于JSON转换
    private final ObjectMapper objectMapper = new ObjectMapper();

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
//        //获取请求路径
//        String requestURI = request.getRequestURI();

//        //判断请求类型
//        if (requestURI.contains("/getAllLike")) {
//            System.out.println("第一放行");
//            return true;
//        }

        // 放行预检请求
        if ("OPTIONS".equalsIgnoreCase(request.getMethod())) {
            response.setStatus(HttpServletResponse.SC_OK);
            return false;  // 这里返回 false 表示拦截器链不继续，但预检请求直接返回 200，浏览器通过
        }

        //获取请求头的token
        String token = request.getHeader("token");

        //判断token是否存在
        if (token == null || token.isEmpty()) {
            writeResult(response, Result.Error("未登录")); //令牌不存在
            return false;
        }

        //校验token
        try {
            JwtUtil.getClaimsFromToken(token);
        } catch (Exception e) {
            writeResult(response, Result.Error("登录失效或非法")); //令牌校验失败
            return false;
        }

        //放行
        return true;
    }

    // 封装写入响应的方法
    private void writeResult(HttpServletResponse response, Result result) throws Exception {
        response.setContentType("application/json;charset=UTF-8");
        response.setStatus(401);
        String json = objectMapper.writeValueAsString(result);
        response.getWriter().write(json);
    }
}
